import { get, post } from "@/utils/request";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Table } from "@/features/tables/data/schema";
import { AxiosPromise } from "axios";

export const tableKeys = {
  all: () => ["tables"] as const,
  lists: () => [...tableKeys.all(), "list"] as const,
  list: (filters: string) => [...tableKeys.lists(), { filters }] as const,
  details: () => [...tableKeys.all(), "detail"] as const,
  detail: (id: number) => [...tableKeys.details(), id] as const,
};

export async function tables(): AxiosPromise {
  return await get<{
    data: Table[];
    count: number;
  }>("/tables/show");
}

export function useTables() {
  return useQuery({
    queryKey: tableKeys.all(),
    queryFn: tables,
  });
}
export interface TableAddData {
  [key: string]: unknown;
}
export async function createTable(data: TableAddData) {
  return await post("/tables/create", data);
}

export function useCreateTable() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: createTable,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: tableKeys.all() });
    },
  });
}

export async function updateTable(data: TableAddData) {
  return await post("/tables/modify", data);
}

export function useUpdateTable() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: updateTable,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: tableKeys.all() });
    },
  });
}

export async function deleteTable(tables: string[]) {
  return await post("/tables/drop", { tables });
}

export function useDeleteTable() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: deleteTable,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: tableKeys.all() });
    },
  });
}
